--[[
    @desc 事件系统核心
    @author zch
    @data:2022-04-18 10:04:00
]]

EventSystem = EventSystem or BaseClass()
local EventSystem = EventSystem

EventSystem.event_id_index = 0

function EventSystem:__init()
	self.event_dictionary = {}
	self.event_id_index_to_key_map = {}
end

function EventSystem:__delete()
	EventSystem.UnBindAll(self)
end

function EventSystem:Bind(event_key, event_func)
	if event_key == nil then
		print("nil event_key:")
		return
	end
	if event_func == nil then
		print("nil event_func:")
		return
	end
	local event_list = self.event_dictionary[event_key]
	if event_list == nil then
		event_list = {}
		self.event_dictionary[event_key] = event_list
	end
	EventSystem.event_id_index = EventSystem.event_id_index + 1
	self.event_id_index_to_key_map[EventSystem.event_id_index] = event_key
	event_list[EventSystem.event_id_index] = event_func
	return EventSystem.event_id_index
end

function EventSystem:UnBind(event_id)
	if event_key == nil then
		print("try to unbind nil event_key:")
		return
	end
	local event_key = self.event_id_index_to_key_map[event_id]
	if event_key then
		self.event_id_index_to_key_map[event_id] = nil
		local event_list = EventSystem.getEvent(self, event_key)
		if event_list then
			event_list[event_id] = nil
		end
	end
end

function EventSystem:UnBindAll()
	self.event_dictionary = {}
	self.event_id_index_to_key_map = {}
end

function EventSystem:Fire(event_key, ...)
	if event_key == nil then
		print("try to fire nil event_key:")
		return
	end
	local event_list = EventSystem.getEvent(self, event_key)
	if event_list then
		for event_id, event_func in pairs(event_list) do
			if event_func then
				event_func(...)
			end
		end
	end
end

function EventSystem:getEvent(event_key)
	return self.event_dictionary[event_key]
end